<template>
  <div class="building-type-list">
    <!-- 建筑类型配置区域 -->
    <div class="building-config-section">
      <el-card class="config-card" shadow="never">
        <div class="config-content">
          <div class="config-header">
            <h3>平台公共建筑类型配置</h3>
            <div class="header-actions">
              <el-button type="primary" @click="handleSave" :loading="saving">
                保存配置
              </el-button>
              <el-button @click="handleReset">重置</el-button>
            </div>
          </div>
          <!-- 基础建筑类型选择器 -->
          <BuildingTypeSelector
            v-model="selectedCategories"
            :max-select="10"
            @change="handleCategoryChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 建筑类型列表展示 -->
    <div class="list-section">
      <BuildingTypeTable 
        :data="buildingTypeList" 
        :loading="loading"
        @edit="handleEdit"
        @delete="handleDelete"
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editForm.id ? '编辑建筑类型' : '新增建筑类型'"
      width="600px"
      :close-on-click-modal="false"
      @close="handleEditDialogClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="120px"
      >
        <el-form-item label="建筑类型名称" prop="buildingTypeName">
          <el-input
            v-model="editForm.buildingTypeName"
            placeholder="请输入建筑类型名称"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="建筑类型编码" prop="buildingTypeCode">
          <el-input
            v-model="editForm.buildingTypeCode"
            placeholder="请输入建筑类型编码"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="建筑类型描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入建筑类型描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number
            v-model="editForm.sortOrder"
            :min="0"
            :max="9999"
            placeholder="请输入排序"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSave" :loading="editSaving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { House, Refresh, InfoFilled } from '@element-plus/icons-vue'
import BuildingTypeSelector from '@/components/BuildingTypeSelector/index.vue'
import BuildingTypeTable from '@/components/BuildingTypeTable/index.vue'
import { buildingTypeApi, type PropertyCompanyBuildingType, type CreateBuildingTypeDTO } from '@/api/buildingType'

// 定义接口
interface Pagination {
  current: number
  size: number
  total: number
}

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const editSaving = ref(false)
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()

const selectedCategories = ref<number[]>([])
const combinedResult = ref<string>('')
const buildingTypeList = ref<PropertyCompanyBuildingType[]>([])

// 分页数据
const pagination = ref<Pagination>({
  current: 1,
  size: 10,
  total: 0
})

// 编辑表单数据
const editForm = reactive<CreateBuildingTypeDTO>({
  id: undefined,
  buildingTypeName: '',
  buildingTypeCode: '',
  categoryIds: [],
  description: '',
  sortOrder: 0,
  status: 1
})

// 表单验证规则
const editRules: FormRules = {
  buildingTypeName: [
    { required: true, message: '请输入建筑类型名称', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  buildingTypeCode: [
    { required: true, message: '请输入建筑类型编码', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '长度不能超过 500 个字符', trigger: 'blur' }
  ]
}

// 获取平台公共建筑类型列表
const loadBuildingTypeList = async () => {
  try {
    loading.value = true
    const response = await buildingTypeApi.getPublicBuildingTypeList({
      current: pagination.value.current,
      size: pagination.value.size
    })
    
    if (response.code === 200) {
      buildingTypeList.value = response.data.records || []
      pagination.value.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '加载建筑类型列表失败')
      buildingTypeList.value = []
    }
  } catch (error) {
    console.error('加载建筑类型列表失败:', error)
    ElMessage.error('加载建筑类型列表失败')
    buildingTypeList.value = []
  } finally {
    loading.value = false
  }
}

// 处理分类选择变化
const handleCategoryChange = (categories: number[], result: string) => {
  selectedCategories.value = categories
  combinedResult.value = result
}

// 处理保存配置
const handleSave = async () => {
  if (selectedCategories.value.length === 0) {
    ElMessage.warning('请至少选择一个建筑类型分类')
    return
  }

  try {
    saving.value = true
    
    // 构建建筑类型数据
    const buildingTypeData: CreateBuildingTypeDTO = {
      buildingTypeName: combinedResult.value,
      buildingTypeCode: generateBuildingTypeCode(combinedResult.value),
      categoryIds: selectedCategories.value,
      description: `平台公共建筑类型：${combinedResult.value}`,
      sortOrder: 0,
      status: 1
    }

    const response = await buildingTypeApi.createBuildingType(buildingTypeData)
    if (response.code === 200) {
      ElMessage.success('建筑类型配置保存成功')
      // 重新加载列表
      await loadBuildingTypeList()
      // 重置选择
      selectedCategories.value = []
      combinedResult.value = ''
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存建筑类型配置失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 处理重置
const handleReset = () => {
  selectedCategories.value = []
  combinedResult.value = ''
}

// 生成建筑类型编码
const generateBuildingTypeCode = (name: string): string => {
  return name.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, '').toUpperCase()
}

// 处理编辑
const handleEdit = (row: PropertyCompanyBuildingType) => {
  editForm.id = row.id
  editForm.buildingTypeName = row.buildingTypeName
  editForm.buildingTypeCode = row.buildingTypeCode
  editForm.description = row.description || ''
  editForm.sortOrder = row.sortOrder || 0
  editForm.status = row.status
  editForm.categoryIds = row.categoryIds || []
  
  editDialogVisible.value = true
}

// 处理删除
const handleDelete = async (row: PropertyCompanyBuildingType) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除建筑类型"${row.buildingTypeName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await buildingTypeApi.deleteBuildingType(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      await loadBuildingTypeList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除建筑类型失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理编辑保存
const handleEditSave = async () => {
  try {
    await editFormRef.value?.validate()
    
    editSaving.value = true
    
    // 使用UpdateBuildingTypeDTO类型进行更新
    const updateData = {
      id: editForm.id!,
      buildingTypeName: editForm.buildingTypeName,
      buildingTypeCode: editForm.buildingTypeCode,
      categoryIds: editForm.categoryIds,
      description: editForm.description,
      sortOrder: editForm.sortOrder,
      status: editForm.status
    }
    
    const response = await buildingTypeApi.updateBuildingType(updateData)
    if (response.code === 200) {
      ElMessage.success('保存成功')
      editDialogVisible.value = false
      await loadBuildingTypeList()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存建筑类型失败:', error)
      ElMessage.error('保存失败')
    }
  } finally {
    editSaving.value = false
  }
}

// 处理编辑对话框关闭
const handleEditDialogClose = () => {
  editFormRef.value?.resetFields()
  // 重置编辑表单
  Object.assign(editForm, {
    id: undefined,
    buildingTypeName: '',
    buildingTypeCode: '',
    categoryIds: [],
    description: '',
    sortOrder: 0,
    status: 1
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadBuildingTypeList()
})
</script>

<style scoped>
.building-type-list {
  padding: 20px;
}

.company-selection-card {
  margin-bottom: 20px;
}

.selection-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.company-selection-content {
  padding: 20px;
}

.company-checkbox {
  margin-right: 20px;
  margin-bottom: 10px;
}

.form-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.building-config-section {
  margin-top: 20px;
}

.config-card {
  margin-bottom: 20px;
}

.config-content {
  padding: 20px 0;
}

.config-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.config-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.list-section {
  margin-top: 20px;
}

/* 多公司显示样式 */
.multi-company-section {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.company-building-section {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  background-color: #fafafa;
  position: relative;
}

.company-building-section:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.company-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #409eff;
}

.company-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.company-header .el-tag {
  font-size: 12px;
}

/* 单公司显示样式 */
.single-company-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e4e7ed;
}

/* 编辑对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
